package com.zzdzz.fileencryption.service.impl;

import com.zzdzz.fileencryption.common.convension.exception.ClientException;
import com.zzdzz.fileencryption.common.result.Results;
import com.zzdzz.fileencryption.service.FileEncryptionService;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


/**
 * 文件加密服务实现层
 */
@Service
public class FileEncryptionServiceImpl implements FileEncryptionService {

    // 字符移位的位数
    private static final int SHIFT = 4;
    // 最大文件大小限制（30MB）
    private static final long MAX_FILE_SIZE = 30 * 1024 * 1024;

    /**
     * 处理文件（加密/解密）
     */
    @Override
    public byte[] processFile(MultipartFile file, boolean isEncrypt) throws IOException {
        // 验证文件
        validateFile(file);

        // 读取文件内容
        byte[] fileContent = file.getBytes();

        // 处理每个字节（加密+4，解密-4）
        for (int i = 0; i < fileContent.length; i++) {
            if (isEncrypt) {
                fileContent[i] += SHIFT;
            } else {
                fileContent[i] -= SHIFT;
            }
        }

        return fileContent;
    }

    /**
     * 生成新的文件名
     */
    @Override
    public String generateNewFilename(String originalFilename, boolean isEncrypt) {
        if (originalFilename == null || originalFilename.isEmpty()) {
            return isEncrypt ? "encrypted.txt" : "decrypted.txt";
        }

        // 分割文件名和扩展名
        int lastDotIndex = originalFilename.lastIndexOf('.');
        String namePart;
        String extension;

        if (lastDotIndex == -1) {
            namePart = originalFilename;
            extension = ".txt";
        } else {
            namePart = originalFilename.substring(0, lastDotIndex);
            extension = originalFilename.substring(lastDotIndex);
        }

        // 添加加密/解密后缀
        String suffix = isEncrypt ? "_encrypted" : "_decrypted";
        return namePart + suffix + extension;
    }

    /**
     * 创建响应头
     */
    @Override
    public HttpHeaders createResponseHeaders(String filename) {
        HttpHeaders headers = new HttpHeaders();
        try {
            // 处理中文文件名编码
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
            headers.add(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename*=UTF-8''" + encodedFilename);
            headers.add(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
        } catch (Exception e) {
            // 编码失败时使用默认文件名_result
            headers.add(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + (filename.contains(".") ? filename + "_result" : filename + "_result.txt"));
        }
        return headers;
    }

    /**
     * 验证文件是否符合要求
     */
    private void validateFile(MultipartFile file) throws IllegalArgumentException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new ClientException(String.format("上传的文件不能为空喵~"));
        }
        // 检查文件类型（是否为txt文件）
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".txt")) {
            throw new ClientException(String.format("目前只支持上传TXT文件喵~"));
        }

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new ClientException(String.format("文件大小不能超过30MB喵~"));
        }

    }
}

